package com.boge.modules.sys.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

@Controller
@RequestMapping({"/file/fileController"})
public class FileController {

    public static final String basePath = "D:/SysFile/ShopFile";

    @PostMapping("/upload")
    @ResponseBody
    public String fileUpload(MultipartFile file) throws IOException {
        if(file != null){
            String oldName = file.getOriginalFilename();
            File imgFile = new File(basePath);
            if(!imgFile.exists()){
                imgFile.mkdir();
            }
            // 上传的文件名称
            String newName = new Date().getTime() + oldName.substring(oldName.lastIndexOf("."));
            File fileImg = new File(imgFile,newName);
            file.transferTo(fileImg);
            return newName;
        }
        return "error";
    }

    @GetMapping("/download")
    public void download(String fileName, HttpServletRequest request, HttpServletResponse response) throws IOException {
        if(StringUtils.isBlank(fileName)|| "null".equals(fileName) || "undefined".equals(fileName)){
            return ;
        }

        // 处理文件上传
        InputStream in = new FileInputStream(basePath+"/"+fileName);
        int size = in.available();
        byte data[] = new byte[size];
        in.read(data);
        in.close();
        response.setContentType("image/jpg");
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(data);
        outputStream.flush();
    }

    @GetMapping("/downloadFile")
    public void downloadFile(String fileName, HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 处理文件上传
        InputStream in = new FileInputStream(basePath+"/"+fileName);

        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);

        int size = in.available();
        byte data[] = new byte[size];
        in.read(data);
        in.close();
        //response.setContentType("image/jpg");
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(data);
        outputStream.flush();
    }
}
